package com.yxsk.relay.job.admin.web.controller;

import com.yxsk.relay.job.admin.data.entity.BaseEntity;
import com.yxsk.relay.job.admin.data.service.AbstractService;
import com.yxsk.relay.job.admin.web.common.exception.RelayAdminWebRuntimeException;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Stream;

/**
 * @Author 11376
 * @CreaTime 2019/6/26 20:47
 * @Description
 */
public abstract class BaseController<T extends BaseEntity, S extends AbstractService> {

    protected static final String MULTIPLE_DATA_SEPARATOR = ",";

    @Autowired
    protected S service;

    /**
     * @Author 11376
     * @Description 启用
     * @CreateTime 2019/6/26 20:47
     * @Return
     */
    @PostMapping("/delete")
    @ResponseBody
    public ResultResponse delete(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] idS = ids.split(MULTIPLE_DATA_SEPARATOR);
            if (idS != null) {
                Stream.of(idS).forEach(id -> {
                    BaseEntity entity = service.findById(id);
                    if (entity != null) {
                        entity.setDelFlag(BaseEntity.DelFlagEnum.DELETED.getFlag());
                        this.service.updateById(entity);
                    }
                });
            }
        }
        return ResultResponse.ok("success");
    }

    @GetMapping("/add")
    public String toAdd() {
        return getBasicDir() + "/add";
    }

    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, Model model) {
        BaseEntity entity = this.service.findById(id);
        if (entity == null) {
            throw new RelayAdminWebRuntimeException("未找到相关信息");
        }
        model.addAttribute("entity", entity);
        return getBasicDir() + "/add";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") String id, Model model) {
        BaseEntity entity = this.service.findById(id);
        if (entity == null) {
            throw new RelayAdminWebRuntimeException("未找到相关信息");
        }
        model.addAttribute("entity", entity);
        return getBasicDir() + "/detail";
    }

    @PostMapping("/save")
    @ResponseBody
    public ResultResponse save(T t) {
        t.setDelFlag(BaseEntity.DelFlagEnum.NORMAL.getFlag());
        this.service.addEntity(t);
        return ResultResponse.ok("操作成功");
    }

    protected abstract String getBasicDir();

}
